import os
import logging
from typing import Dict, Any
from django.utils import timezone
from django.db import transaction

from spark.models import VideoAnswer, AudioAnalysis, AudioFrameData
from .audio_analyzer import perform_full_audio_analysis

logger = logging.getLogger(__name__)


def analyze_video_audio_sync(video_answer_id: str) -> Dict[str, Any]:
    """
    同步分析视频答案的音频
    
    Args:
        video_answer_id: 视频答案ID
        
    Returns:
        分析结果字典
    """
    try:
        # 获取视频答案
        video_answer = VideoAnswer.objects.get(id=video_answer_id)
        
        # 检查视频文件是否存在
        if not video_answer.video_url or not os.path.exists(video_answer.video_url.path):
            return {
                'status': 'error',
                'message': f'Video file not found: {video_answer.video_url.path if video_answer.video_url else "None"}'
            }
        
        # 获取用户性别
        gender = video_answer.session.application.candidate.gender or 'unknown'
        
        # 更新分析状态为处理中
        audio_analysis, created = AudioAnalysis.objects.get_or_create(
            video_answer=video_answer,
            defaults={
                'analysis_status': 'processing',
                'gender': gender
            }
        )
        
        if not created:
            audio_analysis.analysis_status = 'processing'
            audio_analysis.save()
        
        # 执行音频分析
        analysis_result = perform_full_audio_analysis(video_answer.video_url.path, gender)
        
        # 保存分析结果
        with transaction.atomic():
            # 更新音频分析记录
            audio_analysis.gender = analysis_result.get('gender', gender)
            audio_analysis.transcribed_text = analysis_result.get('transcribed_text', '')
            audio_analysis.word_count = analysis_result.get('word_count', 0)
            audio_analysis.speech_duration_seconds = analysis_result.get('speech_duration_seconds', 0.0)
            audio_analysis.overall_audio_score = analysis_result.get('overall_audio_score', 0.0)
            audio_analysis.speed_score = analysis_result.get('speed_score', 0.0)
            audio_analysis.speech_rate_syllables_per_second = analysis_result.get('speech_rate_syllables_per_second', 0.0)
            audio_analysis.pitch_score = analysis_result.get('pitch_score', 0.0)
            audio_analysis.average_pitch_frequency_hz = analysis_result.get('average_pitch_frequency_hz', 0.0)
            audio_analysis.volume_score = analysis_result.get('volume_score', 0.0)
            audio_analysis.average_volume_db = analysis_result.get('average_volume_db', 0.0)
            audio_analysis.pause_score = analysis_result.get('pause_score', 0.0)
            audio_analysis.total_pause_frequency_per_second = analysis_result.get('total_pause_frequency_per_second', 0.0)
            audio_analysis.fluency_score = analysis_result.get('fluency_score', 0.0)
            audio_analysis.articulation_rate_syllables_per_second = analysis_result.get('articulation_rate_syllables_per_second', 0.0)
            audio_analysis.articulation_rate_score = analysis_result.get('articulation_rate_score', 0.0)
            audio_analysis.correction_count_per_second = analysis_result.get('correction_count_per_second', 0.0)
            audio_analysis.correction_count_score = analysis_result.get('correction_count_score', 0.0)
            audio_analysis.f2_slope_hz_per_ms = analysis_result.get('f2_slope_hz_per_ms', 0.0)
            audio_analysis.f2_slope_score = analysis_result.get('f2_slope_score', 0.0)
            audio_analysis.analysis_status = analysis_result.get('analysis_status', 'failed')
            audio_analysis.error_message = analysis_result.get('error', '')
            audio_analysis.save()
            
            # 删除旧的帧数据
            AudioFrameData.objects.filter(audio_analysis=audio_analysis).delete()
            
            # 保存帧数据
            frame_data = analysis_result.get('frame_data', [])
            frame_objects = []
            
            for frame in frame_data:
                frame_objects.append(
                    AudioFrameData(
                        audio_analysis=audio_analysis,
                        timestamp=frame.get('timestamp', 0.0),
                        pitch=frame.get('pitch', 0.0),
                        volume=frame.get('volume', 0.0),
                        pitch_score_per_second=frame.get('pitch_score_per_second', 0.0),
                        volume_score_per_second=frame.get('volume_score_per_second', 0.0)
                    )
                )
            
            if frame_objects:
                AudioFrameData.objects.bulk_create(frame_objects)
        
        return {
            'status': 'success',
            'message': 'Audio analysis completed successfully',
            'analysis_id': audio_analysis.id,
            'frame_count': len(frame_data)
        }
        
    except VideoAnswer.DoesNotExist:
        return {
            'status': 'error',
            'message': f'VideoAnswer with id {video_answer_id} not found'
        }
    except Exception as e:
        logger.error(f"Error analyzing video audio: {e}")
        return {
            'status': 'error',
            'message': str(e)
        }


def analyze_video_audio_async(video_answer_id: str) -> Dict[str, Any]:
    """
    异步分析视频答案的音频（预留接口）
    
    Args:
        video_answer_id: 视频答案ID
        
    Returns:
        任务状态字典
    """
    # 这里可以集成Celery等异步任务队列
    # 目前直接调用同步版本
    return analyze_video_audio_sync(video_answer_id) 